(function() {
  app.service('quoteApi', function($q) {
    this.QuoteApi = require('QuoteApi')({
      url: './quoteapi'
    });

    this.query = function(quote) {
      var deferred = $q.defer();

      var send_buffer = quote.pack();
      var http = new XMLHttpRequest();
      http.open('POST', quote.post_option, true);
      http.responseType = 'arraybuffer';
      http.onload = function(oEvent) {
        var arrayBuffer = this.response;
        if (arrayBuffer) {
          try {
            var data = quote.unpack(arrayBuffer);
            deferred.resolve(data);
          } catch (err) {
            deferred.reject(err);
          }
        }
      };
      http.onerror = function() {
        deferred.reject(new Error('行情请求异常'));
      };
      http.send(send_buffer);
      return deferred.promise;
    };
  });
})(angular);
